import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import styles from './index.module.less';
import HowToPlayMask from './HowToPlayMask';
import MenuMask from './MenuMask';
import socket from '@/socket';
import RoundDetailMask from './RoundDetailMask';
import ProvablyMask from './ProvablyMask';
import { useRecoilState } from 'recoil';
import { PLAY_SETTING, RoundDetailState } from '../../state';

const Bottom = () => {
  const [mines, setMines] = useState(0);
  const [winAmount, setWinAmount] = useState(0);
  const [howToPlayMaskMaskVisible, setHowToPlayMaskVisible] = useState(false);
  const [menuMaskVisible, setMenuMaskVisible] = useState(false);
  const [roundDetail = {}, setRoundDetailState] = useRecoilState(RoundDetailState);
  let timer = useRef();


  useEffect(() => {
    const listen = (msg: Msg) => {
      const { userInfo = {} } = msg.body || {};
      const { money = 0 } = userInfo;
      setMines(money);
    };
    const SETTLE_RESULTlisten = (msg: Msg) => {
      const { money = 0 } = msg.body;
      setMines(money || 0);
      setRoundDetailState(msg.body || {});
    };
    const BET_AND_SETTLE_RESULTlisten = (msg: Msg) => {
      if (!msg.success && msg.code === "EXISTS_NOT_COMPLETION_GAME") {
        socket.send({ msgType: 'USER_INFO' });
        return
      }
      const { money = 0 } = msg.body;
      setMines(money || 0);
    };

    socket.listen(['USER_INFO_RESULT'], listen);
    socket.listen(['SETTLE_RESULT'], SETTLE_RESULTlisten);
    socket.listen(['BET_AND_SETTLE_RESULT'], BET_AND_SETTLE_RESULTlisten);
    return () => {
      socket.unListen(listen);
      socket.unListen(SETTLE_RESULTlisten);
      socket.unListen(BET_AND_SETTLE_RESULTlisten);
    };
  }, []);

  useEffect(() => {
    if (roundDetail.prizeAmount) {
      if (timer.current) {
        clearTimeout(timer.current);
      }
      setWinAmount((roundDetail.prizeAmount).toFixed(2));
      timer.current = setTimeout(() => {
        setWinAmount(0);
      }, 2000);
    }

  }, [roundDetail])

  return (
    <div className={styles.Bottom}>
      <div className={styles.flexLine}>
        <i className={styles.question} onClick={() => {
          setHowToPlayMaskVisible(true);
        }}></i>
        <div className={styles.flex}>
          {
            winAmount > 0 && <div className={styles.greenBtn}>
              +{winAmount}₹
            </div>
          }
          <div className={styles.num}>{mines}₹</div>
          <div id='menuIcon' className={styles.icon} onClick={() => {
            setMenuMaskVisible(true);
          }}></div>
        </div>
      </div>

      <HowToPlayMask
        visible={howToPlayMaskMaskVisible}
        onClose={() => setHowToPlayMaskVisible(false)}
      />
      <MenuMask
        visible={menuMaskVisible}
        onClose={() => setMenuMaskVisible(false)}
      />
      <RoundDetailMask />
      <ProvablyMask
      />
    </div>
  );
};

export default Bottom;